﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using CampusSite.Support.Extensions;
using System.Net;


namespace CampusSite.Models.Mail
{

    public class Url
    {
        public static string GetPhysicalPath()
        {
            return HttpContext.Current.Request.PhysicalApplicationPath;
        }

        public static string GetPhysicalPath(string textToAppend)
        {
            return "{0}{1}".FormatWith(GetPhysicalPath(), textToAppend);
        }

        public static string GetPathFromRoot(string pathWithoutRoot)
        {
            string applicationPath = HttpContext.Current.Request.ApplicationPath;

            return GetPathFromRoot(pathWithoutRoot, applicationPath);
        }

        public static string GetPathFromRoot(string pathWithoutRoot, string applicationPath)
        {
            var pathToReturn = new StringBuilder(applicationPath);

            if (!pathWithoutRoot.StartsWith("/") && !applicationPath.EndsWith("/"))
            {
                pathToReturn.Append("/");
            }

            pathToReturn.Append(pathWithoutRoot);

            return pathToReturn.ToString();
        }


        public static string AppendSlash(string url)
        {
            if (!url.EndsWith("/"))
            {
                url = string.Format("{0}/", url);
            }

            return url;
        }
    }
    public class Resources
    {
        /// <summary>
        /// cid:companylogo
        /// </summary>
        /// 
        
       public  static LinkedResource Logo = new LinkedResource(Url.GetPhysicalPath(@"Content\Images\logo_everis.png")) { ContentId = "companylogo" };
    }


    public class Mail
    {
        private static readonly string MailAccount = ConfigurationManager.AppSettings["infoMailAccount"];
        public string Body {get; set;}
        public string Subject{get;set;}
        public bool InsertLogo { get; set; }
        public string mailToAddress { get; set; }
        //public  void SendEmail(Mail mailTo)
        //{
            
        //    var msgMail = new MailMessage(MailAccount, mailTo.mailToAddress);
            
        //        msgMail.IsBodyHtml = true;
        //        msgMail.Body = this.Body;
        //        msgMail.Subject = this.Subject;
            

        //    if (InsertLogo)
        //    {
        //        var alternateView = AlternateView.CreateAlternateViewFromString(this.Body,
        //                                                                        null,
        //                                                                        MediaTypeNames.Text.Html);

        //        alternateView.LinkedResources.Add(Resources.Logo);

        //        msgMail.AlternateViews.Add(alternateView);
        //    }

        //    try
        //    {
        //        new SmtpClient().Send(msgMail);
        //    }
        //    catch { }

        //}

        //public void Send()
        //{
        //    MailAddress mailfrom = new MailAddress("from@gmail.com");
        //    MailAddress mailto = new MailAddress("to@gmail.com");
        //    MailMessage newmsg = new MailMessage(mailfrom, mailto);

        //    newmsg.Subject = "Subject of Email";
        //    newmsg.Body = "Body(message) of email";

        //    ////For File Attachment, more file can also be attached

        //    Attachment att = new Attachment("G:\\code.txt");
        //    newmsg.Attachments.Add(att);

        //    SmtpClient smtps = new SmtpClient(ConfigurationManager.AppSettings["MailHost"], 587);
        //    smtps.UseDefaultCredentials = false;
        //    smtps.Credentials = new NetworkCredential("urmail", "password");
        //    smtps.EnableSsl = true;
        //    smtps.Send(newmsg);
        
        //}
        public void  Send(Campus.Entities.User user)
        {
            string usuarioMail = ConfigurationManager.AppSettings["MailUserName"];
            string passwordMail = ConfigurationManager.AppSettings["MailPassword"];
            
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
            mail.To.Add(user.UserName);
            mail.From = new MailAddress(usuarioMail, "Campus Crecer");
            mail.Subject = string.Format("{0}, Active su usuario en Campus Crecer", user.UserName);
            mail.SubjectEncoding = System.Text.Encoding.UTF8;

            //reemplazo el controlador actual por el nuevo controlador cuando el usuario confirme su mail
            //string urlConfirmacion = string.Format("{0}/{1}",HttpContext.Current.Request.Url.AbsoluteUri.Replace("Register","Bienvenido"),user.UsuarioEncriptado);

            string urlConfirmacion = string.Format("{0}://{1}/{2}/{3}",HttpContext.Current.Request.Url.Scheme,HttpContext.Current.Request.Url.Host, "Account/Bienvenido", user.UsuarioEncriptado); 

            //http://localhost:60227/Account/Bienvenido/

            StringBuilder body = new StringBuilder();

            body.Append("<b>ACTIVE SU CUENTA.</b> <br/><hr/> ");
            body.Append("Gracias por registrarse en la escuela de futbol <b>Campus Crecer</b>. <br/><br/>");
            body.Append("Para proceder con la activación de su cuenta, ingrese a la siguiente dirección: <br/><br/>");
            body.Append(urlConfirmacion);
            body.Append("<br/><br/>IMPORTANTE: Recuerde y proteja la información de su cuenta de acceso a Campus Crecer:<br/>");
            body.Append(string.Format("<br/>Usuario: {0} ",user.UserName ));
            body.Append(string.Format("<br/>Password: {0} ", user.Password));
            body.Append("<br/><br/>Por favor, NO RESPONDA ESTE MENSAJE.<br/>");
            body.Append("Atentamente. <br/>");
            body.Append("Campus Crecer.");
            mail.Body = body.ToString();
                           
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true;
            mail.Priority = MailPriority.High;
            SmtpClient client = new SmtpClient();
            client.Host = ConfigurationManager.AppSettings["MailHost"];
            if (client.DeliveryMethod != SmtpDeliveryMethod.SpecifiedPickupDirectory)
            {
                client.Credentials = new System.Net.NetworkCredential(usuarioMail, passwordMail);
                client.Port = int.Parse(ConfigurationManager.AppSettings["MailPort"]);
                client.EnableSsl = bool.Parse(ConfigurationManager.AppSettings["MailEnableSsl"]);
            }
            try
            {
                client.Send(mail);
            }
            catch (Exception ex)
            {                
                throw;
                //Page.RegisterStartupScript("UserMsg", "<script>alert('Sending Failed...');if(alert){ window.location='SendMail.aspx';}</script>");
            }
        
        }
    }
}